import type { ProColumns } from '@ant-design/pro-table';
import ExportJsonExcel from 'js-export-excel';
interface ExportExcelType {
  columns: any;
  fileName: string;
  maps: any;
  selectedRows: any;
}
export const exportExcel = ({ columns, fileName, maps, selectedRows }: ExportExcelType) => {
  const columnsData: ProColumns[] = [];
  const option = { fileName: fileName, datas: {} };
  const sheetFilter = [];
  const sheetHeader = [];
  const columnWidths = [];
  for (let i = 0; i < columns.length; i++) {
    if (!columns[i].hideInTable) {
      if (maps[columns[i].dataIndex]) {
        if (
          maps[columns[i].dataIndex].show === true &&
          maps[columns[i].dataIndex].order === undefined
        ) {
          columnsData.push(columns[i]);
          sheetFilter.push(columns[i].dataIndex);
          sheetHeader.push(columns[i].title);
          columnWidths.push(10);
        }
        if (maps[columns[i].dataIndex].show !== false && maps[columns[i].dataIndex].order >= 0) {
          columnsData[maps[columns[i].dataIndex].order] = columns[i];
          sheetFilter[maps[columns[i].dataIndex].order] = columns[i].dataIndex;
          sheetHeader[maps[columns[i].dataIndex].order] = columns[i].title;
          columnWidths[maps[columns[i].dataIndex].order] = 10;
        }
      } else {
        columnsData.push(columns[i]);
        sheetFilter.push(columns[i].dataIndex);
        sheetHeader.push(columns[i].title);
        columnWidths.push(10);
      }
    }
  }
  option.datas = [
    {
      sheetData: selectedRows.map((item: any) => {
        const result = {};
        columnsData.forEach((c: any) => {
          if (!c.hideInTable) {
            result[c.dataIndex] = item[c.dataIndex];
          }
        });
        return result;
      }),
      sheetFilter: sheetFilter.filter((item) => item),
      sheetHeader: sheetHeader.filter((item) => item),
      columnWidths: columnWidths.filter((item) => item),
    },
  ];
  const toExcel = new ExportJsonExcel(option);
  toExcel.saveExcel();
};
